//
//  UserSettingViewController.m
//  KEREN
//
//  Created by MW on 2023/3/24.
//

#import "UserSettingViewController.h"
#import "KRSettingCell.h"
#import "NewsSettingsCell.h"
#import "EditUserNameVC.h"
#import "EditUserPhoneVC.h"
#import "ChangePassWorldVC.h"
#import "KRFeedbackViewController.h"
#import "KRAboutWeViewController.h"

@interface UserSettingViewController ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *messageArr;
@property (nonatomic, strong) NSArray *appMessageArr;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) NSDictionary *dict;
@property (nonatomic, assign) int userSetId;

@end

@implementation UserSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"设置"];
    _titleArr = @[@"头像",@"昵称",@"更换手机号",@"修改登录密码",@"Touch ID/Face ID登录"];
    [self configMessage];
    _appMessageArr = @[@"意见反馈",@"关于我们",@"注销帐号"];
    //@[@"语言服务",@"语言设置",@"意见反馈",@"关于我们"];
    [self getUserSetting];
    self.tableView.tableFooterView = [self footView];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(faceLoginRegiseter) name:FACEIDLOGIN object:nil];
    [center addObserver:self selector:@selector(faceLoginClose) name:@"FACEIDLOGIN_Close" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

-(void)configMessage{
    DeviceInfo *deviceInfo = [UserInfoManager sharedInstance].currentDeviceInfo;
    NSMutableArray *array = [NSMutableArray array];
    SmartItem *item;
    if(deviceInfo.deviceConfig.abnormal){
        item = [SmartItem createSmartItem:@"异常震动" sub_title:@"车辆发生异常震动" imgName:@"" type:SmartType_Abnormal];
        [array addObject:item];
    }
    if(deviceInfo.deviceConfig.cut_power){
        item = [SmartItem createSmartItem:@"切断电源" sub_title:@"未充满电切断电源" imgName:@"" type:SmartType_CutPower];
        [array addObject:item];
    }
    if(deviceInfo.deviceConfig.charging_monitoring){
        item = [SmartItem createSmartItem:@"充电监测" sub_title:@"充电进程中电池温度，电压超过阈值" imgName:@"" type:SmartType_Charge_Monitor];
        [array addObject:item];
    }
    if(deviceInfo.deviceConfig.anti_theft_alarm){
        item = [SmartItem createSmartItem:@"防盗报警"  sub_title:@"车辆异常移动或设备被破坏" imgName:@"" type:SmartType_Anti_Theft_Alarm];
        [array addObject:item];
    }
    if(deviceInfo.deviceConfig.fault_message){
        item = [SmartItem createSmartItem:@"故障消息" sub_title:@"需具体车辆开启上报功能" imgName:@"" type:SmartType_Fault_Message];
        [array addObject:item];
    }
    self.messageArr = array;
}

- (void)getUserSetting{
    WEAKSELF
    [NetworkingTool POST:Device_userSetting_detail parameters:@{} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            weakSelf.dict = response[@"data"];
            weakSelf.userSetId = [weakSelf.dict[@"id"] intValue];
            [weakSelf.tableView reloadData];
        }else{
           // [[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)loginOut{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USERPHONE];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[KRAlartManager shareInstance] hidenLodingImageView];
        [[UserInfoManager sharedInstance] loginOut];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:USERPHONE];
    });
}

-(void)deleteAccount{
    WEAKSELF
    [NetworkingTool POST:User_delete parameters:@{} isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            [weakSelf loginOut];
        }else{
            [[KRAlartManager shareInstance] showErrorAlert:response[@"msg"]];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
            
    }];
}

-(void)toApplication:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        KRFeedbackViewController *vc = [[KRFeedbackViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.row == 1){
        KRAboutWeViewController *vc = [[KRAboutWeViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        WEAKSELF
        [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"注销帐号" decTitle:@"确定要注销当前帐号吗?" cancleBtnText:@"取消" andOkBtnText:@"确定" sucessBlock:^(BOOL isSucess) {
            if(isSucess){
                [weakSelf deleteAccount];
            }
        }];
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return _titleArr.count;
    }else if(section == 1 && self.messageArr.count > 0){
        return _messageArr.count;
    }else{
        return _appMessageArr.count;
    }

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2 + (_messageArr.count > 0 ? 1 : 0);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    headView.backgroundColor = Main_BackColor;
    UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(24, 16, DEVICE_WIDTH - 50, 20)];
    if(section == 0){
        titleLbl.text = @"个人资料";
    }else if(section == 1 && self.messageArr.count > 0){
        titleLbl.text = @"消息设置";
        UIView *tipsView = [[UIView alloc] initWithFrame:CGRectMake(24, 46, DEVICE_WIDTH - 48, 116)];
        tipsView.layer.borderWidth = 1;
        tipsView.layer.borderColor = rgba(0.53, 0.54, 0.56, 0.4).CGColor;
        tipsView.layer.cornerRadius = 25;
        tipsView.clipsToBounds = YES;
        UILabel *tipsLbl = [UILabel setLblText:@"1.开启提示后，车辆发生以下情况会推送消息到APP提醒您。\n2.具体功能需要配置范围值的需要进入详细的车辆进行配置。" font:Font(14) withColor:Color_86898E inSubView:tipsView];
        tipsLbl.frame = CGRectMake(12, 12, DEVICE_WIDTH - 48 - 24, 116 - 24);
        tipsLbl.numberOfLines = 0;
        [headView addSubview:tipsView];
    }else{
        titleLbl.text = @"应用信息";

    }
    titleLbl.textColor = Color_86898E;
    titleLbl.font = Font(14);
    [headView addSubview:titleLbl];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 1 && self.messageArr.count > 0){
        return 172;
    }else{
        return 45;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1 && self.messageArr.count > 0){
        return 70;
    }else{
        return 60;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
        cell.on_offswitch.hidden = YES;
        cell.photoIcon.hidden = YES;
        cell.decLbl.text = @"";
        cell.nameLbl.text = _titleArr[indexPath.row];
        cell.rightIcon.hidden = NO;
        if(indexPath.row == _titleArr.count - 1){
            cell.lineView.hidden = YES;
        }else{
            cell.lineView.hidden = NO;
        }
        UserInfo *user = USERINFO;
        if(indexPath.row == 0){
            cell.rightIcon.hidden = YES;
            cell.photoIcon.hidden = NO;
            [cell.photoIcon sd_setImageWithURL:[NSURL URLWithString:user.picture] placeholderImage:[UIImage imageNamed:@"user_default_icon"] options:SDWebImageRefreshCached];
        }else if (indexPath.row == 1){
            cell.decLbl.text = user.name;
        }else if (indexPath.row == 2){
            cell.decLbl.text = user.phone;
        }else if(indexPath.row == 4){
            cell.on_offswitch.hidden = NO;
            cell.rightIcon.hidden = YES;
            cell.on_offswitch.tag = indexPath.row;
            cell.on_offswitch.on = [_dict[@"face"] boolValue];
            [[NSUserDefaults standardUserDefaults] setBool:cell.on_offswitch.on forKey:[NSString stringWithFormat:@"isFaceIdLogin_%@",user.phone]];
            [cell.on_offswitch addTarget:self action:@selector(isOpenFace:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
    }else if(indexPath.section == 1 && self.messageArr.count > 0){
        SmartItem *item = self.messageArr[indexPath.row];
        NewsSettingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsSettingsCell"];
        cell.titleLbl.text = item.title;
        cell.decLbl.text = item.sub_title;
        if(indexPath.row == _messageArr.count - 1){
            cell.lineView.hidden = YES;
        }else{
            cell.lineView.hidden = NO;
        }
        if(item.type == SmartType_Abnormal){
            cell.isOpenSwitch.on = [_dict[@"vibration"] boolValue];
        }else if(item.type == SmartType_CutPower){
            cell.isOpenSwitch.on = [_dict[@"cut_power"] boolValue];
        }else if(item.type == SmartType_Charge_Monitor){
            cell.isOpenSwitch.on = [_dict[@"charge_monitor"] boolValue];
        }else if(item.type == SmartType_Anti_Theft_Alarm){
            cell.isOpenSwitch.on = [_dict[@"guard_alarm"] boolValue];
        }else if(item.type == SmartType_Fault_Message){
            cell.isOpenSwitch.on = [_dict[@"fault_alarm"] boolValue];
        }
        cell.isOpenSwitch.tag = item.type;
        [cell.isOpenSwitch addTarget:self action:@selector(isOpen:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
        cell.on_offswitch.hidden = YES;
        cell.photoIcon.hidden = YES;
        cell.rightIcon.hidden = NO;
        cell.decLbl.text = @"";
        cell.nameLbl.text = _appMessageArr[indexPath.row];
        if(indexPath.row == _appMessageArr.count - 1){
            cell.lineView.hidden = YES;
        }else{
            cell.lineView.hidden = NO;
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UserInfo *user = USERINFO;
    if(indexPath.section == 0){
        if(indexPath.row == 0){
            [[FlieUploadManager shareInstance] getossToken];
            TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
            imagePC.allowTakePicture = YES;
            imagePC.allowTakeVideo = NO;
            imagePC.allowPickingVideo = NO;
            imagePC.allowPickingGif = NO;
            imagePC.showSelectedIndex = YES;
            imagePC.allowPickingOriginalPhoto = YES;//原图
            imagePC.minImagesCount = 0;
            imagePC.showSelectBtn = NO;
            imagePC.allowPreview = YES;
            imagePC.autoSelectCurrentWhenDone = YES;
            imagePC.modalPresentationStyle = 0;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self presentViewController:imagePC animated:YES completion:nil];
            });
        }else if (indexPath.row == 1){
            EditUserNameVC *vc = [[EditUserNameVC alloc] init];
            vc.userName = user.name;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2){
            EditUserPhoneVC *vc = [[EditUserPhoneVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 3){
            ChangePassWorldVC *vc = [[ChangePassWorldVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if(indexPath.section == 1){
        if(self.messageArr.count == 0){
            [self toApplication:indexPath];
        }
    }else{
        [self toApplication:indexPath];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    for (UIImage *img in photos) {
        NSData *imageData = UIImageJPEGRepresentation(img,0.5);
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        [[FlieUploadManager shareInstance] uploadImageToOss:imageData type:0 andCount:1 currentCount:0];
    }
}

- (void)isOpenFace:(UISwitch *)sender{
    int type = 0;
    if(sender.on){
        [[LoginManager sharedInstance] checkUnlockSupportType];
        type = 1;
    }else{
        [self faceLoginClose];
    }
}

- (void)faceLoginClose{
    NSDictionary *dict = @{@"id":@(_userSetId),@"face":@(0)};
    [self updateDeviceSettingforSet:nil andEbickSet:dict];
}

- (void)faceLoginRegiseter{
    NSDictionary *dict = @{@"id":@(_userSetId),@"face":@(1)};
    [self updateDeviceSettingforSet:nil andEbickSet:dict];
}

- (void)isOpen:(UISwitch *)sender{
    int type =sender.on ? 1 : 0;
    if(sender.tag == SmartType_Abnormal){
        NSDictionary *dict = @{@"id":@(_userSetId),@"vibration":@(type)};
        [self updateDeviceSettingforSet:nil andEbickSet:dict];
    }else if (sender.tag == SmartType_CutPower){
        NSDictionary *dict = @{@"id":@(_userSetId),@"cut_power":@(type)};
        [self updateDeviceSettingforSet:nil andEbickSet:dict];
    }
    else if (sender.tag == SmartType_Charge_Monitor){
        NSDictionary *dict = @{@"id":@(_userSetId),@"charge_monitor":@(type)};
        [self updateDeviceSettingforSet:nil andEbickSet:dict];
    }else if (sender.tag == SmartType_Anti_Theft_Alarm){
        NSDictionary *deviceSet = @{@"id":@(_userSetId),@"guard_alarm":@(type)};
        [self updateDeviceSettingforSet:nil andEbickSet:deviceSet];
    }else if (sender.tag == SmartType_Fault_Message){
        NSDictionary *deviceSet = @{@"id":@(_userSetId),@"fault_alarm":@(type)};
        [self updateDeviceSettingforSet:nil andEbickSet:deviceSet];
    }

}
- (void)updateDeviceSettingforSet:(NSDictionary *)deviceSet andEbickSet:(NSDictionary *)dcit{
    NSDictionary *parameters;
    if(deviceSet){
        parameters = deviceSet;
    }else{
        parameters = dcit;
    }
    WEAKSELF
    [NetworkingTool POST:Device_userSetting_update parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf getUserSetting];
        //[weakSelf.tableView reloadData];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
   // Device_setting_update
}


- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRSettingCell" bundle:nil] forCellReuseIdentifier:@"KRSettingCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsSettingsCell" bundle:nil] forCellReuseIdentifier:@"NewsSettingsCell"];

        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)footView{
    if(!_footView){
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 150)];
        _footView.backgroundColor = [UIColor clearColor];
        UIButton *loginOutBtn = [UIButton setButtonWithTitle:@"退出登录" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
        [_footView addSubview:loginOutBtn];
        [loginOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.right.offset(-24);
            make.height.offset(58);
            make.top.offset(40);
        }];
        [loginOutBtn addTarget:self action:@selector(loginOut) forControlEvents:UIControlEventTouchUpInside];
    }
    return _footView;
}

@end
